package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.core.helper.DictHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.EduAreaCodeEnum;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.core.dao.model.EduClass;
import com.jwsoft.manager.core.dao.model.EduClassStudentKey;
import com.jwsoft.manager.core.dao.service.EduClassService;
import com.jwsoft.manager.core.dao.service.EduClassStudentKeyService;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.jwsoft.manager.common.vo.eduClassAdviser.EduClassAdviserVO;
import com.jwsoft.manager.common.vo.eduClassAdviser.EduClassAdviserKeyVO;
import com.jwsoft.manager.common.vo.eduClassAdviser.EduClassAdviserQueryVO;
import com.jwsoft.manager.core.integration.EduClassAdviserIntegration;
import com.jwsoft.manager.core.dao.service.EduClassAdviserService;
import com.jwsoft.manager.core.dao.model.EduClassAdviser;
/**
 * 班主任基础信息表业务实现类
 *
 * @author zhiyuan
 * @since 2023-08-21
 */
@ApiService(funcCode = "eduClassAdviser", title = "班主任基础信息表")
public class EduClassAdviserIntegrationImpl implements EduClassAdviserIntegration {

    @Autowired
    public EduClassAdviserService eduClassAdviserService;

    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private DictHelper dictHelper;

    @Autowired
    private EduSchoolService eduSchoolService;

    @Autowired
    private EduClassService eduClassService;

    @Autowired
    private EduClassStudentKeyService eduClassStudentKeyService;

    @Override
    @OpApi(funcCode = "eduClassAdviser0001", title = "班主任基础信息表分页查询", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduClassAdviserVO> getList(EduClassAdviserQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        // if (ObjectUtils.isEmpty(vo.getAreaCode())){
        //     vo.setAreaCode(SessionUtil.getAreaCode());
        // }
        if (ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }
        if (!ObjectUtils.isEmpty(vo.getSearchText())) {
            vo.setFullName(vo.getSearchText());
        }
        if (StringUtils.isNotBlank(vo.getSchoolId())) {
            EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(vo.getSchoolId());
            if (eduSchoolVO != null) {
                vo.setAreaCode(eduSchoolVO.getAreaCode());
            } else {
                vo.setSchoolId(null);
            }
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduClassAdviser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(EduClassAdviser::getYear,vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getAreaCode()),EduClassAdviser::getAreaCode, vo.getAreaCode())
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), EduClassAdviser::getSchoolId, vo.getSchoolId());

        queryWrapper.lambda()
                .eq(!ObjectUtils.isEmpty(vo.getAdviserId()),EduClassAdviser::getAdviserId,vo.getAdviserId())
                .eq(!ObjectUtils.isEmpty(vo.getIdcard()),EduClassAdviser::getIdcard,vo.getIdcard())
                .like(!ObjectUtils.isEmpty(vo.getFullName()),EduClassAdviser::getFullName,vo.getFullName())
                .orderByDesc(EduClassAdviser::getCreateTime,EduClassAdviser::getFullName);
        List<EduClassAdviser> list = eduClassAdviserService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduClassAdviser> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduClassAdviserVO> resultList = Convert.toList(EduClassAdviserVO.class, pageInfo.getList());
        // 转义数据字典值
         dictHelper.valueToName(resultList, Arrays.asList(EduAreaCodeEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduClassAdviser0002", title = "班主任基础信息表根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduClassAdviserVO getById(EduClassAdviserKeyVO vo) {
        EduClassAdviser entity = eduClassAdviserService.getById(vo.getAdviserId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduClassAdviserVO result = Convert.convert(EduClassAdviserVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduClassAdviser0003", title = "班主任基础信息表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduClassAdviserVO vo) {
        if (ObjectUtils.isEmpty(vo.getAdviserId())){
            //主键为空为新增校验

        }else{
            //主键不为空为修改校验

        }
        //通用字段校验
        if (ObjectUtils.isEmpty(vo.getFullName())){
            throw new AppException("姓名不能为空");
        }
        if (ObjectUtils.isEmpty(vo.getIdcard())){
            throw new AppException("身份证不能为空");
        }
        boolean xsFlag = IdcardUtil.isValidCard(vo.getIdcard());
        if (xsFlag) {
            if (StringUtils.isBlank(vo.getSex())) {
                int gender = IdcardUtil.getGenderByIdCard(vo.getIdcard());
                if (gender == 1) {
                    // 男
                    vo.setSex("1");
                } else {
                    // 女
                    vo.setSex("2");
                }
            }
        }
        if (ObjectUtils.isEmpty(vo.getSchoolId())){
            throw new AppException("所属学校不能为空");
        }
        if (ObjectUtils.isEmpty(vo.getAreaCode())){
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        if (ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }
    }

    @Override
    @OpApi(funcCode = "eduClassAdviser0004", title = "班主任基础信息表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduClassAdviser0004",
            operationName = "班主任基础信息表新增",
            dataType = "adviserId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduClassAdviserVO add(EduClassAdviserVO vo) {
        //保存前校验
        checkSave(vo);
        EduSchoolVO school = eduSchoolService.getDetail(vo.getSchoolId());
        vo.setSchoolName(school.getShortName());
        long count = eduClassAdviserService.count(Wrappers.<EduClassAdviser>lambdaQuery()
                .eq(EduClassAdviser::getYear,vo.getYear())
                .eq(EduClassAdviser::getIdcard, vo.getIdcard()));
        if (count >0){
            throw new AppException(vo.getFullName()+"已存在，无需再进行新增了");
        }
        //保存数据
        EduClassAdviser entity = Convert.convert(EduClassAdviser.class, vo);
        eduClassAdviserService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setAdviserId(entity.getAdviserId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduClassAdviser0005", title = "班主任基础信息表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduClassAdviser0005",
            operationName = "班主任基础信息表修改",
            dataType = "adviserId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduClassAdviserVO edit(EduClassAdviserVO vo) {
        if (ObjectUtils.isEmpty(vo.getAdviserId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduClassAdviser oldEntity = eduClassAdviserService.getById(vo.getAdviserId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        Integer year = eduHelper.thisYear();
        String areaCode = SessionUtil.getAreaCode();
        if (!oldEntity.getSchoolId().equals(vo.getSchoolId())){
            //查询是否能修改学校信息
            QueryWrapper<EduClass> eduClassQueryWrapper = new QueryWrapper<>();
            eduClassQueryWrapper.lambda()
                    .eq(EduClass::getYear,year)
                    .eq(EduClass::getAreaCode,areaCode)
                    .eq(EduClass::getAdviserId,vo.getAdviserId());
            long eduClassCount = eduClassService.count(eduClassQueryWrapper);
            if (eduClassCount >0){
                throw new AppException(oldEntity.getFullName()+"已被任用，无法修改所属学校!");
            }
            QueryWrapper<EduClassStudentKey> keyQueryWrapper = new QueryWrapper<>();
            keyQueryWrapper.lambda()
                    .eq(EduClassStudentKey::getYear,year)
                    .eq(EduClassStudentKey::getAreaCode,areaCode)
                    .eq(EduClassStudentKey::getAdviserId,vo.getAdviserId());
            long studentKeyCount = eduClassStudentKeyService.count(keyQueryWrapper);
            if (studentKeyCount >0){
                throw new AppException(oldEntity.getFullName()+"已被任用，无法修改所属学校!");
            }
            EduSchoolVO school = eduSchoolService.getDetail(vo.getSchoolId());
            vo.setSchoolName(school.getShortName());
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduClassAdviser entity = Convert.convert(EduClassAdviser.class, vo);
        eduClassAdviserService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduClassAdviser0006", title = "班主任基础信息表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduClassAdviser0006",
            operationName = "班主任基础信息表删除",
            dataType = "adviserId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduClassAdviserKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getAdviserId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduClassAdviser entity = eduClassAdviserService.getById(vo.getAdviserId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        Integer year = eduHelper.thisYear();
        String areaCode = SessionUtil.getAreaCode();
        //判断班主任是否能进行删除
        QueryWrapper<EduClass> eduClassQueryWrapper = new QueryWrapper<>();
        eduClassQueryWrapper.lambda()
                .eq(EduClass::getYear,year)
                .eq(EduClass::getAreaCode,areaCode)
                .eq(EduClass::getAdviserId,vo.getAdviserId());
        long eduClassCount = eduClassService.count(eduClassQueryWrapper);
        if (eduClassCount >0){
            throw new AppException(entity.getFullName()+"已被任用，无法删除!");
        }
        QueryWrapper<EduClassStudentKey> keyQueryWrapper = new QueryWrapper<>();
        keyQueryWrapper.lambda()
                .eq(EduClassStudentKey::getYear,year)
                .eq(EduClassStudentKey::getAreaCode,areaCode)
                .eq(EduClassStudentKey::getAdviserId,vo.getAdviserId());
        long studentKeyCount = eduClassStudentKeyService.count(keyQueryWrapper);
        if (studentKeyCount >0){
            throw new AppException(entity.getFullName()+"已被任用，无法删除!");
        }
        eduClassAdviserService.removeById(vo.getAdviserId());
    }
}
